package com.ruoyi.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.merchant.domain.BaseDeviceInfo;
import com.ruoyi.merchant.domain.CustomerBase;
import com.ruoyi.merchant.domain.ReminderSettings;
import com.ruoyi.merchant.dto.BaseDeviceInfoDto;
import com.ruoyi.merchant.mapper.BaseDeviceInfoMapper;
import com.ruoyi.merchant.mapper.CustomerBaseMapper;
import com.ruoyi.merchant.mapper.ReminderSettingsMapper;
import com.ruoyi.merchant.msg.Model.*;
import com.ruoyi.merchant.producer.BaseDevice;
import com.ruoyi.merchant.producer.KafkaProducer;
import com.ruoyi.merchant.service.IBaseDeviceInfoService;
import com.ruoyi.merchant.util.H002ModelCmdEnum;
import com.ruoyi.merchant.vo.BaseDeviceInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 * 
 * @author chengxin.ju
 * @date 2023-12-12
 */
@Slf4j
@Service
public class BaseDeviceInfoServiceImpl implements IBaseDeviceInfoService 
{
    @Autowired
    private BaseDeviceInfoMapper baseDeviceInfoMapper;
    @Autowired
    KafkaProducer kafkaMessageProducer;
    @Autowired
    private ReminderSettingsMapper reminderSettingsMapper;

    /**
     * 查询设备信息
     * 
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public BaseDeviceInfoVo selectBaseDeviceInfoById(String id)
    {
        BaseDeviceInfoVo baseDeviceInfoVo = new BaseDeviceInfoVo();
        BaseDeviceInfo baseDeviceInfo = baseDeviceInfoMapper.selectBaseDeviceInfoById(id);
        BeanUtils.copyProperties(baseDeviceInfo,baseDeviceInfoVo);
        ReminderSettings reminderSettings = new ReminderSettings();
        reminderSettings.setDeviceId(id);
        List<ReminderSettings> reminderSettingsList = reminderSettingsMapper.selectReminderSettingsList(reminderSettings);
        baseDeviceInfoVo.setReminderSettingsList(reminderSettingsList);
        return baseDeviceInfoVo;
    }

    /**
     * 查询设备信息列表
     * 
     * @param baseDeviceInfo 设备信息
     * @return 设备信息
     */
    @Override
    public List<BaseDeviceInfo> selectBaseDeviceInfoList(BaseDeviceInfo baseDeviceInfo)
    {
        return baseDeviceInfoMapper.selectBaseDeviceInfoList(baseDeviceInfo);
    }

    @Autowired
    private RedisService redisService;

    /**
     * 新增设备信息
     *
     * @param baseDeviceInfo 设备信息
     * @return 结果
     */
    @Override
    public BaseDeviceInfo insertBaseDeviceInfo(BaseDeviceInfo baseDeviceInfo)
    {
        baseDeviceInfo.setId(UUID.fastUUID().toString(true));
        baseDeviceInfo.setCreateTime(DateUtils.getNowDate());
        if (StringUtils.isEmpty(baseDeviceInfo.getImie()) && StringUtils.isNotEmpty(baseDeviceInfo.getMac())){
            baseDeviceInfo.setImie(baseDeviceInfo.getMac());
        }

        if (StringUtils.isEmpty(baseDeviceInfo.getCustomerId())){
            throw new RuntimeException("客户id 不能为为空");
        }
        if (StringUtils.isEmpty(baseDeviceInfo.getImie())){
            throw new RuntimeException("设备识别码 不能为为空");
        }
        if (StringUtils.isNotEmpty(baseDeviceInfo.getCustomerId())
                && StringUtils.isNotEmpty(baseDeviceInfo.getImie())){
            String object = "";
            if (redisService.hasKey(H002ModelCmdEnum.DEVICE_MODEL)){
                object = redisService.getObject(H002ModelCmdEnum.DEVICE_MODEL);
            }
            Map<String,String> cacheMap = JSONObject.parseObject(object,Map.class);
            if (cacheMap == null){
                cacheMap = new HashMap<>();
            }
            cacheMap.put(baseDeviceInfo.getImie(),baseDeviceInfo.getCustomerId());
            redisService.setObject(H002ModelCmdEnum.DEVICE_MODEL, JSONObject.toJSONString(cacheMap));
        }
        baseDeviceInfoMapper.insertBaseDeviceInfo(baseDeviceInfo);
        return baseDeviceInfo;
    }

    /**
     * 修改设备信息
     *
     * @param baseDeviceInfoDto 设备信息
     * @return 结果
     */
    @Override
    public BaseDeviceInfo updateBaseDeviceInfo(BaseDeviceInfoDto baseDeviceInfoDto) throws UnsupportedEncodingException {
        baseDeviceInfoDto.setUpdateTime(DateUtils.getNowDate());


//        if (StringUtils.isNotEmpty(baseDeviceInfoDto.getCustomerId())
//                && StringUtils.isNotEmpty(baseDeviceInfoDto.getImie())){
//            String object = "";
//            if (redisService.hasKey(H002ModelCmdEnum.DEVICE_MODEL)){
//                object = redisService.getObject(H002ModelCmdEnum.DEVICE_MODEL);
//            }
//            Map<String,String> cacheMap = JSONObject.parseObject(object,Map.class);
//            if (cacheMap == null){
//                cacheMap = new HashMap<>();
//            }
//            cacheMap.put(baseDeviceInfoDto.getImie(),baseDeviceInfoDto.getCustomerId());
//            redisService.setObject(H002ModelCmdEnum.DEVICE_MODEL, JSONObject.toJSONString(cacheMap));
//        }
        baseDeviceInfoMapper.updateBaseDeviceInfo(baseDeviceInfoDto);
        //发送指令
        send(baseDeviceInfoDto);
        return baseDeviceInfoDto;
    }

    public void send(BaseDeviceInfoDto baseDeviceInfoDto) throws UnsupportedEncodingException {
        log.info("初始化设置终端----------------------------------start---------------------");
        log.info("初始化数据:{}", JSON.toJSONString(baseDeviceInfoDto.toString()));

        /**
         * 更新类别  【4G】sos号码设置 0 ; 【4G】GPS定位周期设置 1 ;  【4G】心率血压测量周期设置  2
         *      * 【4G】体澧测量罔期设置  3  【4G】跌倒报警设置  4  【4G】 睡眠时何段设置  5   【4G】 血压校准  6 【4G】  阙钟设置总开关 7
         *      * 【4G】 时区设置 8  【4G】 工作模式设置 9  【4G】 白名单设置 10 【4G】 闹钟提醒 11  【4G】白名单设置  12【4G】 重启
         */
        if (baseDeviceInfoDto.getModel() == null){
            return;
        }
        if (baseDeviceInfoDto.getModel().intValue() == 0){
            BP12 bp12 = new BP12();
            bp12.setImei(baseDeviceInfoDto.getImie());
            bp12.setPhones(baseDeviceInfoDto.getSosPhones());
            bp12.setSerialNnumber(UUID.fastUUID().toString(true));
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp12.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 1) {
            BP34 bp34 = new BP34();
            bp34.setImei(baseDeviceInfoDto.getImie());
            bp34.setSerialNnumber(UUID.fastUUID().toString(true));
            bp34.setFrequency(baseDeviceInfoDto.getGpsCycle().intValue());
            bp34.setGps(baseDeviceInfoDto.getGpsSwitch().toString());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp34.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 2) {
            BP86 bp86 = new BP86();
            bp86.setImei(baseDeviceInfoDto.getImie());
            bp86.setSerialNnumber(UUID.fastUUID().toString(true));
            bp86.setTime(baseDeviceInfoDto.getHeartRateCycle().toString());
            bp86.setOpen(baseDeviceInfoDto.getOpenHeartRateCycle().toString());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp86.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 3) {
            BP87 bp87 = new BP87();
            bp87.setImei(baseDeviceInfoDto.getImie());
            bp87.setSerialNnumber(UUID.fastUUID().toString(true));
            bp87.setTime(baseDeviceInfoDto.getMeasurementCycle().toString());
            bp87.setOpen(baseDeviceInfoDto.getOpenMeasurementCycle().toString());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp87.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 4) {
            BP77 bp77 = new BP77();
            bp77.setImei(baseDeviceInfoDto.getImie());
            bp77.setSerialNnumber(UUID.fastUUID().toString(true));
            bp77.setSensitive(baseDeviceInfoDto.getFallAlarmSensitivity().toString());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp77.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 5) {
            BP96 bp96 = new BP96();
            bp96.setImei(baseDeviceInfoDto.getImie());
            bp96.setSerialNnumber(UUID.fastUUID().toString(true));
            bp96.setTime(baseDeviceInfoDto.getSleepSet());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp96.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 6) {
            BPJZ bpjz = new BPJZ();
            bpjz.setImei(baseDeviceInfoDto.getImie());
            bpjz.setSerialNnumber(UUID.fastUUID().toString(true));
            bpjz.setUp(baseDeviceInfoDto.getBloodPressureHigh().toString());
            bpjz.setLow(baseDeviceInfoDto.getBloodPressureLow().toString());
            bpjz.setAge(baseDeviceInfoDto.getBloodPressureAge().toString());
            bpjz.setSex(baseDeviceInfoDto.getBloodPressureSex().toString());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bpjz.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 7) {
            List<ReminderSettings> reminderSettingsList = baseDeviceInfoDto.getReminderSettingsList();
            List<BP85.Item>   itemList = new ArrayList<>();
            BP85.Item item = new BP85.Item();
            for (ReminderSettings reminderSettings:  reminderSettingsList) {
                item = new BP85.Item();
                item.setTime(reminderSettings.getTime());
                item.setType(reminderSettings.getCode());
                item.setSw(String.valueOf(reminderSettings.getOpen()));
                item.setCycle(String.valueOf(reminderSettings.getRepetMode()));
                itemList.add(item);
            }
            BP85 bp85 = new BP85();
            bp85.setImei(baseDeviceInfoDto.getImie());
            bp85.setSerialNnumber(UUID.fastUUID().toString(true));
            bp85.setSw(baseDeviceInfoDto.getAlarmSwitch().toString());
            bp85.setItems(itemList);
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp85.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 8) {
            BP20 bp20 = new BP20();
            bp20.setImei(baseDeviceInfoDto.getImie());
            bp20.setSerialNnumber(UUID.fastUUID().toString(true));
            bp20.setLanguage("0");
            bp20.setTimeZone(baseDeviceInfoDto.getTimeZone());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp20.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 9) {
            BP33 bp33 = new BP33();
            bp33.setImei(baseDeviceInfoDto.getImie());
            bp33.setSerialNnumber(UUID.fastUUID().toString(true));
            bp33.setWorkingMode(baseDeviceInfoDto.getWorkMode().toString());
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp33.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 10) {
            BP14 bp14 = new BP14();
            bp14.setImei(baseDeviceInfoDto.getImie());
            bp14.setSerialNnumber(UUID.fastUUID().toString(true));
            bp14.setPhones(baseDeviceInfoDto.getWhiteList().getBytes("UNICODE"));
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp14.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 11) {
//            BPJZ bpjz = new BPJZ();
//            bpjz.setImei(baseDeviceInfoDto.getImie());
//            bpjz.setSerialNnumber(UUIDUtils.getUuid32());
//            bpjz.setUp(baseDeviceInfoDto.getBloodPressureHigh().toString());
//            bpjz.setLow(baseDeviceInfoDto.getBloodPressureLow().toString());
//            bpjz.setAge(baseDeviceInfoDto.getBloodPressureAge().toString());
//            bpjz.setSex(baseDeviceInfoDto.getBloodPressureSex().toString());
//            kafkaMessageProducer.send(BaseDevice.KAFKA_TOPIC, baseDeviceInfoDto.getImie(), bpjz.toString());
        } else if (baseDeviceInfoDto.getModel().intValue() == 12) {
            BP18 bp18 = new BP18();
            bp18.setImei(baseDeviceInfoDto.getImie());
            bp18.setSerialNnumber(UUID.fastUUID().toString(true));
            kafkaMessageProducer.sendMessage(BaseDevice.KAFKA_TOPIC, bp18.toString());
        }


        log.info("初始化设置终端----------------------------------end---------------------");
    }

    /**
     * 批量删除设备信息
     * 
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteBaseDeviceInfoByIds(String[] ids)
    {
        return baseDeviceInfoMapper.deleteBaseDeviceInfoByIds(ids);
    }

    /**
     * 删除设备信息信息
     * 
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteBaseDeviceInfoById(String id)
    {
        return baseDeviceInfoMapper.deleteBaseDeviceInfoById(id);
    }

    @Override
    public int execUnbind(BaseDeviceInfo baseDeviceInfo) {
        if (StringUtils.isNotEmpty(baseDeviceInfo.getImie())){
            String object = "";
            if (redisService.hasKey(H002ModelCmdEnum.DEVICE_MODEL)){
                object = redisService.getObject(H002ModelCmdEnum.DEVICE_MODEL);
            }
            Map<String,String> cacheMap = JSONObject.parseObject(object,Map.class);
            if (cacheMap == null){
                cacheMap = new HashMap<>();
            }
            cacheMap.remove(baseDeviceInfo.getImie());
            redisService.setObject(H002ModelCmdEnum.DEVICE_MODEL, JSONObject.toJSONString(cacheMap));
        }
        return baseDeviceInfoMapper.execUnbind(baseDeviceInfo);
    }

    @Autowired
    private CustomerBaseMapper customerBaseMapper;

    @Override
    public AjaxResult execBinding(BaseDeviceInfo baseDeviceInfo) {

        CustomerBase customerBase = new CustomerBase();
        customerBase.setId(baseDeviceInfo.getCustomerId());
        if (StringUtils.isNotEmpty(baseDeviceInfo.getMac())){
            BaseDeviceInfo base = new BaseDeviceInfo();
            base.setMac(baseDeviceInfo.getMac());
            base.setDel(0L);
            List<BaseDeviceInfo> baseDeviceInfos = baseDeviceInfoMapper.selectBaseDeviceInfoList(base);
            if (CollectionUtils.isEmpty(baseDeviceInfos)){
                baseDeviceInfo.setId(UUID.fastUUID().toString(true));
                baseDeviceInfo.setCreateTime(DateUtils.getNowDate());
                if (StringUtils.isEmpty(baseDeviceInfo.getImie()) && StringUtils.isNotEmpty(baseDeviceInfo.getMac())){
                    baseDeviceInfo.setImie(baseDeviceInfo.getMac());
                }
                baseDeviceInfo.setAppUserId(SecurityUtils.getUserId().toString());
                customerBase.setAppUserId(baseDeviceInfo.getAppUserId());
                baseDeviceInfoMapper.insertBaseDeviceInfo(baseDeviceInfo);
            }else {
                BaseDeviceInfo deviceInfo = baseDeviceInfos.get(0);
                if (!deviceInfo.getAppUserId().equals(baseDeviceInfo.getAppUserId())){
                    return AjaxResult.error("该设备被别人已绑定，请联系先解绑");
                }
                baseDeviceInfo.setImie(deviceInfo.getImie());
                customerBase.setAppUserId(deviceInfo.getAppUserId());
            }
        }

        if (StringUtils.isNotEmpty(baseDeviceInfo.getImie())){
            BaseDeviceInfo base = new BaseDeviceInfo();
            base.setImie(baseDeviceInfo.getImie());
            base.setDel(0L);
            List<BaseDeviceInfo> baseDeviceInfos = baseDeviceInfoMapper.selectBaseDeviceInfoList(base);
            if (CollectionUtils.isEmpty(baseDeviceInfos)){
                baseDeviceInfo.setId(UUID.randomUUID().toString(true));
                baseDeviceInfo.setCreateTime(DateUtils.getNowDate());
                customerBase.setAppUserId(baseDeviceInfo.getAppUserId());
                baseDeviceInfoMapper.insertBaseDeviceInfo(baseDeviceInfo);
            }else {
                BaseDeviceInfo deviceInfo = baseDeviceInfos.get(0);
                if (!deviceInfo.getAppUserId().equals(baseDeviceInfo.getAppUserId())){
                    return AjaxResult.error("该设备被别人已绑定，请联系先解绑");
                }
                customerBase.setAppUserId(deviceInfo.getAppUserId());
            }
        }
        customerBaseMapper.updateCustomerBase(customerBase);
//        redisService.deleteObject(H002ModelCmdEnum.DEVICE_MODEL);
        if (StringUtils.isNotEmpty(baseDeviceInfo.getCustomerId())
                && StringUtils.isNotEmpty(baseDeviceInfo.getImie())){
            String object = "";
            if (redisService.hasKey(H002ModelCmdEnum.DEVICE_MODEL)){
                object = redisService.getObject(H002ModelCmdEnum.DEVICE_MODEL);
            }
            Map<String,String> cacheMap = JSONObject.parseObject(object,Map.class);
            if (cacheMap == null){
                cacheMap = new HashMap<>();
            }
            cacheMap.put(baseDeviceInfo.getImie(),baseDeviceInfo.getCustomerId());
            redisService.setObject(H002ModelCmdEnum.DEVICE_MODEL, JSONObject.toJSONString(cacheMap));
        }
        baseDeviceInfoMapper.execbind(baseDeviceInfo);
        return AjaxResult.success();
    }

    @Override
    public List<BaseDeviceInfoVo> selectBaseDeviceInfoListV2(BaseDeviceInfo baseDeviceInfo) {
        List<BaseDeviceInfoVo> baseDeviceInfoVos = baseDeviceInfoMapper.selectBaseDeviceInfoListV2(baseDeviceInfo);
        baseDeviceInfoVos = baseDeviceInfoVos.stream().map(item->{
            try {
                if (item.getCustomerBirthday() != null){
                    item.setAge(DateUtils.getAge(item.getCustomerBirthday()));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return item;
        }).collect(Collectors.toList());
        return baseDeviceInfoVos;
    }

//    @Autowired
//    private WhiteListMapper whiteListMapper;

    @Override
    public BaseDeviceInfo updateBaseDeviceInfoV2(BaseDeviceInfoDto baseDeviceInfoDto) {
        baseDeviceInfoDto.setUpdateTime(DateUtils.getNowDate());
        baseDeviceInfoMapper.updateBaseDeviceInfo(baseDeviceInfoDto);
//        List<WhiteList> whiteListList = baseDeviceInfoDto.getWhiteListList();
//        if (CollectionUtils.isNotEmpty(whiteListList)){
//            whiteListMapper.deleteWhiteListByBaseDeviceId(baseDeviceInfoDto.getId());
//            for (WhiteList whiteList: whiteListList) {
//                whiteList.setBaseDeviceId(baseDeviceInfoDto.getId());
//                whiteListMapper.insertWhiteList(whiteList);
//            }
//        }
        if (CollectionUtils.isNotEmpty(baseDeviceInfoDto.getReminderSettingsList())){
            List<ReminderSettings> reminderSettingsList = baseDeviceInfoDto.getReminderSettingsList();
            int cun = reminderSettingsMapper.deleteReminderSettingsByBaseDeviceId(baseDeviceInfoDto.getId());
            for (ReminderSettings reminderSettings: reminderSettingsList) {
                reminderSettings.setDeviceId(baseDeviceInfoDto.getId());
                reminderSettingsMapper.insertReminderSettings(reminderSettings);
            }

        }
        return null;
    }
}
